//% color="#1E90FF" iconWidth=50 iconHeight=40
namespace MoonshotAI {

    //% block="初始化kimi API密钥:[API] 模型:[MODEL] 温度:[TEMPERATURE]" blockType="command"
    //% API.shadow="string" API.defl="YOUR_API"
    //% MODEL.shadow="dropdown" MODEL.options="MODEL"
    //% TEMPERATURE.shadow="range" TEMPERATURE.params.max=100 TEMPERATURE.params.min=1 TEMPERATURE.defl="30"
    export function initializeMoonshotAI(parameter: any, block: any) {
        let kimi_api = parameter.API.code;
        let model = parameter.MODEL.code;
        let temperature = parameter.TEMPERATURE.code/100;
        Generator.addImport(`import openai\nimport json`);
        Generator.addCode(`
client = openai.OpenAI(api_key=${kimi_api}, base_url="https://api.moonshot.cn/v1")
kimi_model = "${model}"
kimi_temperature = ${temperature}
kimi_history = [
    {"role": "system", "content": """你是 Kimi，由 Moonshot AI 提供的人工智能助手，
    你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。
    回答问题的时候尽量精简词语，尽量将回答控制在50字以内。
    也不需要在回答中添加关于时效性或者是请注意之类的额外说明"""}
]

def kimi_chat(query, kimi_history, kimi_model, kimi_temperature):
    kimi_history.append({
        "role": "user", 
        "content": query
    })
    completion = client.chat.completions.create(
        model=kimi_model,
        messages=kimi_history,
        temperature=kimi_temperature,
    )
    result = completion.choices[0].message.content
    kimi_history.append({
        "role": "assistant",
        "content": result
    })
    return result
`);
    }

    //% block="发送消息 [MESSAGE] 并返回响应" blockType="reporter"
    //% MESSAGE.shadow="string" MESSAGE.defl="你好，AI"
    export function sendMessage(parameter: any, block: any) {
        let message = parameter.MESSAGE.code;

        Generator.addCode(`kimi_chat(${message},kimi_history, kimi_model, kimi_temperature)`);
    }
    //% block="上传文件 [FILE] " blockType="command"
    //% FILE.shadow="string" FILE.defl="xxx.txt"
    export function uploadFile(parameter: any, block: any) {
        let file = parameter.FILE.code; // 获取文件路径

        Generator.addImport(`from pathlib import Path`);
        Generator.addCode(`
file_path = Path(${file})
file_object = client.files.create(file=file_path, purpose="file-extract")
file_content = client.files.content(file_id=file_object.id).text
kimi_history.append({
    "role": "system",
    "content": file_content
})
`);
    }
}
